import axios from "axios";
import qs from "qs";

const baseAxios = axios.create({
  baseURL: (process.env.NEXT_PUBLIC_BASE_URL as string) + "api",
  timeout: 100 * 1000,
  headers: {
    "Cache-Control": "no-cache",
  },
});

export type postAxiosType = {
  url: string;
  data?: {};
};

export type getAxiosType = {
  url: string;
  params?: {};
};

export function postAxios({ url, data }: postAxiosType) {
  return new Promise((resolve, reject) => {
    baseAxios
      .post(url, qs.stringify(data))
      .then((res) => {
        resolve(res.data);
      })
      .catch((err: any) => {
        console.log("post请求报错了~", err);
        reject(err);
      });
  });
}

export function postFileAxios({ url, data }: postAxiosType) {
  return new Promise((resolve, reject) => {
    baseAxios
      .post(url, data)
      .then((res) => {
        resolve(res.data);
      })
      .catch((err: any) => {
        console.log("post请求报错了~", err);
        reject(err);
      });
  });
}

export function getAxios({ url, params = {} }: getAxiosType) {
  return new Promise((resolve, reject) => {
    baseAxios
      .get(url, {
        ...params,
      })
      .then((res) => {
        resolve(res.data);
      })
      .catch(async (err) => {
        console.log(err, "出错了");
        reject(err);
      });
  });
}

export function getFileAxios({ url, params = {} }: getAxiosType) {
  return new Promise((resolve, reject) => {
    baseAxios
      .get(url)
      .then((res) => {
        resolve(res.data);
      })
      .catch(async (err) => {
        console.log(err, "出错了");
        reject(err);
      });
  });
}

export function easyPost({ url, data }: postAxiosType) {
  return new Promise((resolve, reject) => {
    baseAxios({
      url,
      method: "post",
      headers: { "Content-Type": "multipart/form-data" },
      data,
    })
      .then((res) => {
        resolve(res.data);
      })
      .catch((error) => {
        reject(error);
      });
  });
}
